package com.example.order.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.example.order.R;
import com.example.order.pojo.Consumer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AdminManageUserFragment extends Fragment {

    TextView titleTextView;
    ListView userListView;
    Button addUserButton, editButton, deleteButton, refreshButton;
    private static final String BASE_URL = "http://10.2.0.232:8080/backend-api-endpoint";

    public AdminManageUserFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_manage_user, container, false);

        // Get references to UI elements
        titleTextView = view.findViewById(R.id.titleTextView);
        userListView = view.findViewById(R.id.userListView);
        addUserButton = view.findViewById(R.id.addUserButton);
        editButton = view.findViewById(R.id.editButton);
        deleteButton = view.findViewById(R.id.deleteButton);
        refreshButton = view.findViewById(R.id.refreshButton);

        // Set ListView choice mode
        userListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        addUserButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAddConsumerDialog();
            }
        });

        editButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int selectedPosition = userListView.getCheckedItemPosition();
                if (selectedPosition != ListView.INVALID_POSITION) {
                    Consumer selectedConsumer = (Consumer) userListView.getItemAtPosition(selectedPosition);
                    showEditConsumerDialog(selectedConsumer);
                } else {
                    Toast.makeText(getActivity(), "请先选择要编辑的用户", Toast.LENGTH_SHORT).show();
                }
            }
        });

        refreshButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAllConsumers();
            }
        });

        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int selectedPosition = userListView.getCheckedItemPosition();
                if (selectedPosition != ListView.INVALID_POSITION) {
                    Consumer selectedConsumer = (Consumer) userListView.getItemAtPosition(selectedPosition);
                    showDeleteConfirmationDialog(selectedConsumer);
                } else {
                    Toast.makeText(getActivity(), "请先选择要删除的用户", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // Call the method to get all consumers when the fragment is created
        getAllConsumers();

        return view;
    }

    private class AddConsumerTask extends AsyncTask<Consumer, Void, String> {
        @Override
        protected String doInBackground(Consumer... consumers) {
            OkHttpClient client = new OkHttpClient();
//            String url = "http://10.2.2.204:8080/backend-api-endpoint/addConsumer";
            String url = BASE_URL + "/addConsumer";


            // 构建 JSON 请求体
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            JSONObject json = new JSONObject();
            try {
                json.put("consumer_id", consumers[0].getConsumer_id());
                json.put("consumer_password", consumers[0].getConsumer_password());
                json.put("consumer_name", consumers[0].getConsumer_name());
                json.put("contact", consumers[0].getContact());
                json.put("reservation_result", consumers[0].getReservation_result());
            } catch (JSONException e) {
                e.printStackTrace();
            }

            RequestBody requestBody = RequestBody.create(JSON, json.toString());

            // 构建 HTTP 请求
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();

            try {
                // 执行请求
                Response response = client.newCall(request).execute();

                // 处理响应
                if (response.isSuccessful()) {
                    return response.body().string();
                } else {
                    return "Error: " + response.code();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "Error: " + e.getMessage();
            }
        }

        @Override
        protected void onPostExecute(String result) {
            // 处理结果，例如向用户显示消息
            Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show();
            // 你还可以通过再次调用 getAllConsumers() 来刷新 userListView
            getAllConsumers();
        }
    }

    private class GetAllConsumersTask extends AsyncTask<Void, Void, List<Consumer>> {
        @Override
        protected List<Consumer> doInBackground(Void... voids) {
            OkHttpClient client = new OkHttpClient();
//            String url = "http://10.2.2.204:8080/backend-api-endpoint/getAllConsumers";
            String url = BASE_URL + "/getAllConsumers";

            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();

            try {
                Response response = client.newCall(request).execute();

                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    // 解析获取到的用户列表
                    List<Consumer> consumerList = parseConsumerList(responseBody);
                    return consumerList;
                } else {
                    Log.e("GetAllConsumers", "Error: " + response.code());
                    return null;
                }
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("GetAllConsumers", "Error: " + e.getMessage());
                return null;
            }
        }

        public class ConsumerAdapter extends ArrayAdapter<Consumer> {
            public ConsumerAdapter(Context context, List<Consumer> consumers) {
                super(context, R.layout.admin_list_item_layout, consumers);
            }

            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                if (convertView == null) {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.admin_list_item_layout, parent, false);
                }

                Consumer consumer = getItem(position);

                TextView text1 = convertView.findViewById(R.id.text1);
                TextView text2 = convertView.findViewById(R.id.text2);
                TextView text3 = convertView.findViewById(R.id.text3);

                text1.setText("用户ID: " + consumer.getConsumer_id());
                text2.setText("姓名: " + consumer.getConsumer_name());
                text3.setText("密码: " + consumer.getConsumer_password());

                return convertView;
            }
        }

        @Override
        protected void onPostExecute(List<Consumer> consumerList) {
            if (consumerList != null) {
                // 创建适配器
                AdminManageUserFragment.GetAllConsumersTask.ConsumerAdapter adapter = new GetAllConsumersTask().new ConsumerAdapter(getActivity(), consumerList);

                // 将适配器设置到ListView
                userListView.setAdapter(adapter);

                for (Consumer consumer : consumerList) {
                    Log.d("ConsumerInfo", "ID: " + consumer.getConsumer_id() + ", Name: " + consumer.getConsumer_name());
                    // 根据需要在界面上显示用户信息
                }
            }
        }
    }

    private List<Consumer> parseConsumerList(String responseBody) {
// 实现解析JSON的逻辑，将数据转换成 Consumer 对象列表
        // 这里需要根据您后端返回的数据格式进行解析
        // 示例代码，具体根据实际情况修改
        List<Consumer> consumerList = new ArrayList<>();
        try {
            JSONArray jsonArray = new JSONArray(responseBody);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonConsumer = jsonArray.getJSONObject(i);
                Consumer consumer = new Consumer();
                consumer.setConsumer_id(jsonConsumer.getString("consumer_id"));
                consumer.setConsumer_name(jsonConsumer.getString("consumer_name"));
                consumer.setConsumer_password(jsonConsumer.getString("consumer_password"));
                // 其他字段的解析
                consumerList.add(consumer);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return consumerList;    }

    public void getAllConsumers() {
        new GetAllConsumersTask().execute();
    }

    private void showAddConsumerDialog() {
// 使用 AlertDialog.Builder 创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Add New User");

        // 使用 LayoutInflater 加载自定义布局
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_add_user, null);
        builder.setView(dialogView);

        // 获取对话框中的 EditText
        final EditText etUserId = dialogView.findViewById(R.id.etUserId);
        final EditText etUserName = dialogView.findViewById(R.id.etUserName);
        final EditText etUserPassword = dialogView.findViewById(R.id.etUserPassword);
        final EditText etContact = dialogView.findViewById(R.id.etContact);
        final EditText etReservationResult = dialogView.findViewById(R.id.etReservationResult);

        // 设置对话框按钮
        builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 获取用户输入的信息
                String userId = etUserId.getText().toString();
                String userName = etUserName.getText().toString();
                String userPassword = etUserPassword.getText().toString();
                String contact = etContact.getText().toString();
                String reservationResult = etReservationResult.getText().toString();

                // 判断必填字段是否为空
                if (userId.isEmpty() || userPassword.isEmpty()) {
                    // 提示用户必填字段不能为空
                    Toast.makeText(getActivity(), "User ID and Password are required fields", Toast.LENGTH_SHORT).show();
                } else {
                    // 创建新的 Consumer 对象
                    Consumer newConsumer = new Consumer(userId, userName, userPassword, contact, reservationResult);

                    // 调用添加用户的方法
                    addConsumer(newConsumer);
                }
            }
        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 用户点击取消，不执行任何操作
            }
        });

        // 显示对话框
        builder.create().show();    }

    private void showEditConsumerDialog(final Consumer selectedConsumer) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("编辑用户");

        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_add_user, null);
        builder.setView(dialogView);

        // 获取对话框中的 EditText
        final EditText etUserId = dialogView.findViewById(R.id.etUserId);
        final EditText etUserName = dialogView.findViewById(R.id.etUserName);
        final EditText etUserPassword = dialogView.findViewById(R.id.etUserPassword);
        final EditText etContact = dialogView.findViewById(R.id.etContact);
        final EditText etReservationResult = dialogView.findViewById(R.id.etReservationResult);

        // 预填充数据
        etUserId.setText(selectedConsumer.getConsumer_id());
        etUserName.setText(selectedConsumer.getConsumer_name());
        etUserPassword.setText(selectedConsumer.getConsumer_password());
        etContact.setText(selectedConsumer.getContact());
        etReservationResult.setText(String.valueOf(selectedConsumer.getReservation_result()));

        builder.setPositiveButton("保存", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 获取编辑后的用户信息
                String userId = etUserId.getText().toString();
                String userName = etUserName.getText().toString();
                String userPassword = etUserPassword.getText().toString();
                String contact = etContact.getText().toString();
                String reservationResult = etReservationResult.getText().toString();

                // 更新用户
                Consumer editedConsumer = new Consumer(userId, userName, userPassword, contact, reservationResult);
                editConsumer(selectedConsumer.getConsumer_id(), editedConsumer);
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 用户取消编辑
            }
        });

        builder.create().show();    }

    public void addConsumer(Consumer newConsumer) {
        new AddConsumerTask().execute(newConsumer);
    }

    public void editConsumer(String consumerId, Consumer editedConsumer) {
        new EditConsumerTask().execute(consumerId, editedConsumer);
    }

    private class EditConsumerTask extends AsyncTask<Object, Void, String> {
        @Override
        protected String doInBackground(Object... params) {
            // 获取参数
            String consumerId = (String) params[0];
            Consumer editedConsumer = (Consumer) params[1];

            OkHttpClient client = new OkHttpClient();
//            String url = "http://10.2.2.204:8080/backend-api-endpoint/editConsumer";
            String url = BASE_URL + "/editConsumer";

            // 构建 JSON 请求体
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            JSONObject json = new JSONObject();
            try {
                json.put("consumer_id", editedConsumer.getConsumer_id());
                json.put("consumer_password", editedConsumer.getConsumer_password());
                json.put("consumer_name", editedConsumer.getConsumer_name());
                json.put("contact", editedConsumer.getContact());
                json.put("reservation_result", editedConsumer.getReservation_result());
            } catch (JSONException e) {
                e.printStackTrace();
            }

            RequestBody requestBody = RequestBody.create(JSON, json.toString());

            // 构建 HTTP 请求
            Request request = new Request.Builder()
//                    .url(url + "/" + consumerId)  // 注意：这里可能需要在URL中包含要更新的用户ID
                    .url(url)
                    .post(requestBody)
                    .build();

            try {
                // 执行请求
                Response response = client.newCall(request).execute();

                // 处理响应
                if (response.isSuccessful()) {
                    return response.body().string();
                } else {
                    return "Error: " + response.code();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "Error: " + e.getMessage();
            }
        }

        @Override
        protected void onPostExecute(String result) {
            // 处理结果，例如向用户显示消息
            Log.d("AsyncTaskResult", "Result: " + result);
            Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show();
            // 你还可以通过再次调用 getAllConsumers() 来刷新 userListView
            getAllConsumers();
        }    }

    private void showDeleteConfirmationDialog(final Consumer consumerToDelete) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("确认删除");
        builder.setMessage("确定要删除用户 " + consumerToDelete.getConsumer_id() + " 吗？");

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 用户确认删除，调用删除用户的方法
                deleteConsumer(consumerToDelete.getConsumer_id());
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 用户取消删除
            }
        });

        builder.create().show();    }

    public void deleteConsumer(String consumerId) {
        new DeleteConsumerTask().execute(consumerId);
    }

    private class DeleteConsumerTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String consumerId = params[0];
            OkHttpClient client = new OkHttpClient();
//            String url = "http://10.2.2.204:8080/backend-api-endpoint/deleteConsumer";
            String url = BASE_URL + "/deleteConsumer";

            // 构建 JSON 请求体
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            JSONObject json = new JSONObject();
            try {
                json.put("consumer_id", consumerId);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            RequestBody requestBody = RequestBody.create(JSON, json.toString());

            // 构建 HTTP 请求
            Request request = new Request.Builder()
//                    .url(url + "/" + consumerId)
                    .url(url)
                    .post(requestBody)  // 使用 POST 请求，因为后端接口要求请求体
                    .build();

            try {
                // 执行请求
                Response response = client.newCall(request).execute();

                // 处理响应
                if (response.isSuccessful()) {
                    return response.body().string();
                } else {
                    return "Error: " + response.code();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "Error: " + e.getMessage();
            }
        }

        @Override
        protected void onPostExecute(String result) {
            // 处理结果，例如向用户显示消息
            Log.d("AsyncTaskResult", "Result: " + result);
            Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show();
            // 刷新用户列表
            getAllConsumers();
        }
    }
}
